package Dao;


import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import Entity.Notice;
import mapper.Coursemapper;
import mapper.Noticemapper;
import mapper.Rankmapper;

public class noticedao implements Noticemapper{
	private  static Noticemapper noticemapper;
	private  static SqlSession session;

	public noticedao() throws IOException {
	 	String resource ="mybatis-config.xml";
		InputStream inputstream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlsessionfactory = new SqlSessionFactoryBuilder().build(inputstream);
		 session = sqlsessionfactory.openSession();
        noticemapper = session.getMapper(Noticemapper.class);
    }
	public void close(){
		this.session.close();
	}
	@Override
	//发送通知
	public boolean sendMessage(Notice no) {
		rankdao rm = null;
		try {
			rm = new rankdao();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int notice_Id = rm.getNum("notice_Id");
		no.setNotice_Id(String.valueOf(notice_Id));
		boolean iuser = this.noticemapper.sendMessage(no);
		rm.UpdateNum("notice_Id");
		if(iuser){
			session.commit();
		}else{
			session.rollback();
		}
		
		return iuser;
	}

	@Override
	//根据收件人id查询通知
	public List<Notice> noticeQueryById(String id) {
		
		List<Notice> selectList = this.noticemapper.noticeQueryById(id);
	
		return selectList;
	}

	@Override
	//根据用户id和页码查询信息
	public List<Notice> queryByPage(String uid, int page) {
		Noticemapper nm = null;
		try {
			nm = new noticedao();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<Notice> sel = nm.noticeQueryById(uid);
		//     从第几条数据开始
        int firstIndex = (page - 1) * 1000;
        //	        到第几条数据结束
        int lastIndex = page * 1000;
        
        if(lastIndex<=sel.size())
        	return sel.subList(firstIndex, lastIndex);
        else if(firstIndex>=sel.size())
        	return null;
        else
        	return sel.subList(firstIndex, sel.size());
	}
	
	

	@Override
	//根据信息号查询信息，返回一个Notice实例
	public Notice queryByNid(String nid) {
		
		Notice selectList = this.noticemapper.queryByNid(nid);

		return selectList;
	}

	@Override
	public boolean queryNoticeByUid(String uid) {
	
		boolean selectList = this.noticemapper.queryNoticeByUid(uid);
		
		if(selectList)
			return false;
		else
			return true;
	}

	@Override
	public void setRead(String nid) {
	
		this.noticemapper.setRead(nid);

		session.commit();
	

	}


	
	

}
